

# 导入必要的模块
import random
import pygame as pg
from .. import tool
from .. import constants as c


# 地图类定义
class Map():
    def __init__(self, width, height):
        # 初始化地图的宽度和高度
        self.width = width
        self.height = height
        # 创建一个二维数组来表示地图，初始值为0
        self.map = [[0 for x in range(self.width)] for y in range(self.height)]

    # 检查指定位置是否在地图范围内
    def isValid(self, map_x, map_y):
        if (map_x < 0 or map_x >= self.width or
                map_y < 0 or map_y >= self.height):
            return False
        return True

    # 检查指定位置是否可移动
    def isMovable(self, map_x, map_y):
        return (self.map[map_y][map_x] == c.MAP_EMPTY)

    # 根据实际坐标获取地图索引
    def getMapIndex(self, x, y):
        x -= c.MAP_OFFSET_X
        y -= c.MAP_OFFSET_Y
        return (x // c.GRID_X_SIZE, y // c.GRID_Y_SIZE)

    # 根据地图索引获取网格的中心位置坐标
    def getMapGridPos(self, map_x, map_y):
        return (map_x * c.GRID_X_SIZE + c.GRID_X_SIZE // 2 + c.MAP_OFFSET_X,
                map_y * c.GRID_Y_SIZE + c.GRID_Y_SIZE // 5 * 3 + c.MAP_OFFSET_Y)

    # 设置指定位置的地图网格类型
    def setMapGridType(self, map_x, map_y, type):
        self.map[map_y][map_x] = type

    # 获取一个随机的地图索引
    def getRandomMapIndex(self):
        map_x = random.randint(0, self.width - 1)
        map_y = random.randint(0, self.height - 1)
        return (map_x, map_y)

    # 在指定位置显示植物，返回植物显示的位置
    def showPlant(self, x, y):
        pos = None
        map_x, map_y = self.getMapIndex(x, y)
        # 检查位置是否有效且可移动
        if self.isValid(map_x, map_y) and self.isMovable(map_x, map_y):
            # 获取植物显示的位置
            pos = self.getMapGridPos(map_x, map_y)
        return pos